package com.haiyou.dc.netty.controller.im;

import com.haiyou.common.util.R;
import com.haiyou.dc.netty.entity.ImFriendApply;
import com.haiyou.dc.netty.entity.ImMyFriend;
import com.haiyou.dc.netty.entity.ImUser;
import com.haiyou.dc.netty.entity.dto.SearchOrAddFriendDTO;
import com.haiyou.dc.netty.service.ImFriendApplyService;
import com.haiyou.dc.netty.service.ImMyFriendService;
import com.haiyou.dc.netty.service.ImUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author root
 * @date 2020-03-04 16:05:17
 */
@RestController
@RequestMapping("/im/friend/apply")
@Slf4j
@Api(tags = "APP朋友申请")
public class ImFriendApplyApi {

    @Autowired
    private ImFriendApplyService imFriendApplyService;
    @Autowired
    private ImUserService imUserService;
    @Autowired
    private ImMyFriendService imMyFriendService;

    @ApiOperation(value = "搜索朋友")
    @PostMapping("/searchOrAddFriend")
    public R searchOrAddFriend(@RequestBody SearchOrAddFriendDTO dto) {
        if (dto.getMyId().equals(dto.getFriendId())) {
            return R.error("添加的朋友不能是自己");
        }
        ImUser imUser = imUserService.selectOne(new ImUser().setUsername(dto.getMyId()));
        if (imUser == null) {
            return R.error("当前用户不存在");
        }

        ImUser friendUser = imUserService.selectOne(new ImUser().setUsername(dto.getFriendId()));
        if (friendUser == null) {
            return R.error("添加的朋友不存在");
        }

        int count = imMyFriendService.selectCount(new ImMyFriend()
                .setMyId(dto.getMyId()).setFriendId(dto.getFriendId()));
        if (count > 0) {
            return R.error("该用户已经是你的朋友");
        }

        if (dto.getActionType().equals("search")) {
            return R.ok(friendUser);
        }

        //添加申请消息
        int selectCount = imFriendApplyService.selectCount(new ImFriendApply()
                .setSender(dto.getMyId()).setReceiver(dto.getFriendId()));
        if (selectCount <= 0) {
            ImFriendApply apply = new ImFriendApply().setSender(dto.getMyId()).setReceiver(dto.getFriendId());
            apply.setApplyReason(dto.getApplyReason());
            apply.setApplyTime(new Date());
            imFriendApplyService.insert(apply);
        }
        return R.ok();
    }


}